﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.Framework.Common.Serialization;
using System.Threading;
using ZyGames.DZPocker.Tools;
using System.Globalization;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 请求玩家战绩
	/// </summary>
	public class Action30035 : BaseAction
	{
		private int week = 0;
		private int userId;
		private string firstDateTime;
		private GameUser _gameUser;
		private string tablesStr = "";
		private string title = ""; //2016年第50周总盈亏+0
		private bool result = false;
		private string log = string.Empty;
		private string dayScoreStr = ""; //每一天的盈亏记录Dictionary<DateTime, int>
		private bool nextOrLast = false;//true代表上一周
		public Action30035(HttpGet actionGetter)
			: base((short)ActionType.DZApplyBattleScore, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetString("FirstDateTime", ref firstDateTime) &&
				httpGet.GetBool("NextOrLast", ref nextOrLast) &&
				httpGet.GetInt("UserId", ref userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_gameUser = GameTable.Current.GetUser(userId);
			if (_gameUser == null)
			{
				Tool.WriteWarmingLine("消息30035玩家不存在");
				return false;
			}
			var tableRecords = new List<RecordTable>();
			GregorianCalendar gc = new GregorianCalendar();
			try
			{
				DateTime time;
				DateTime firstDay;
				if (string.IsNullOrEmpty(firstDateTime))
				{
					time = DateTime.Now;
					firstDay = time.AddDays(1 - Convert.ToInt32(time.DayOfWeek.ToString("d"))).Date;
				}
				else if(!nextOrLast)
				{
					//请求一周牌桌
					time = Convert.ToDateTime(firstDateTime);
					var currentWeekFirstDay = time.AddDays(1 - Convert.ToInt32(time.DayOfWeek.ToString("d"))).Date;
					firstDay = currentWeekFirstDay.AddDays(-7);
				}
				else
				{
					//请求下一周的牌桌数据
					time = Convert.ToDateTime(firstDateTime);
					var currentWeekFirstDay = time.AddDays(1 - Convert.ToInt32(time.DayOfWeek.ToString("d"))).Date;
					firstDay = currentWeekFirstDay.AddDays(7);
				}
				int weekOfYear = gc.GetWeekOfYear(firstDay, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
				var year = firstDay.Year;

				//每天的成绩单，前面是这一周的日期
				Dictionary<DateTime, int> dayScore = new Dictionary<DateTime, int>();
				Dictionary<DateTime, int> daySocreSorted = new Dictionary<DateTime, int>();
				//获得所有的时间-上一周的第一天如果在[0,604800)这个时间段里面 则说明是这一周的数据
				var userTables = GameTable.Current.GetUserTableByUserId(userId);
				if (userTables.Count <= 0)
				{
					log = "没有牌局记录";
					result = true;

					title = string.Format("{0}年第{1}周总盈亏{2}", year, weekOfYear, 0);
					dayScoreStr = "";

					for (int i = 0; i < 7; i++)
					{
						var t = firstDay.AddDays(i);
						dayScore.Add(t, 0);
					}
					this.dayScoreStr = Convert.ToBase64String(ProtoBufUtils.Serialize(dayScore));


					//测试数据
					//int offset = 1;
					//for (int i = 0; i < 7; i++)
					//{
					//	var t = firstDay.AddDays(i).Date;
					//	offset = -offset;
					//	var v = offset * i * 30;
					//	dayScore.Add(t, v);
					//}
					//this.dayScoreStr = Convert.ToBase64String(ProtoBufUtils.Serialize(dayScore));
					//result = true;

					return true;
				}
				int totalScoreInWeek = 0;
				foreach (var userTable in userTables)
				{
					//查询table
					var gameTable = GameTable.Current.GetGameTableData(userTable.TableID);
					if (gameTable == null)
						continue;


					//判断当前table的时间是否在当前一周之内
					TimeSpan sp = gameTable.StartTime - firstDay;

					if (sp.TotalSeconds >= 0 && sp.TotalSeconds < 604800)
					{
						var recordTable = new RecordTable() { TableID = userTable.TableID, BeginTime = gameTable.StartTime, TableName = gameTable.TableName, SmallBind = gameTable.SmallBind, TotalTime = gameTable.TableTime, Profit = userTable.Profit, Insurance = gameTable.InsurancerUserID != 0, RoomMaster = new SimpleUserDataWithTexture() { UserId = gameTable.MasterUserId, HeadIcon = gameTable.MasterHeadIcon, NickName = gameTable.MasterNickName } };
						tableRecords.Add(recordTable);
						totalScoreInWeek += userTable.Profit;
						//判断当前桌子时间,然后将成绩单累计上去
						int score;
						var date = gameTable.StartTime.Date;
						if (dayScore.TryGetValue(date, out score))
						{
							score += userTable.Profit;
						}
						else
						{
							dayScore.Add(date, userTable.Profit);
						}
					}
					for (int i = 0; i < 7; i++)
					{
						var t = firstDay.AddDays(i);
						if (!dayScore.ContainsKey(t.Date))
							dayScore.Add(t, 0);
					}
					//根据时间排序
					daySocreSorted = dayScore.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
					dayScore.Clear();
				}
				this.dayScoreStr = Convert.ToBase64String(ProtoBufUtils.Serialize(daySocreSorted));
				var totalScore = totalScoreInWeek > 0 ? ("+" + totalScoreInWeek.ToString()) : totalScoreInWeek.ToString();
				title = string.Format("{0}年第{1}周总盈亏{2}", year, weekOfYear, totalScore);
				tablesStr = Convert.ToBase64String(ProtoBufUtils.Serialize(tableRecords));
			}
			catch (Exception ex)
			{
				Tool.WriteErrorLine("消息30035 序列化报错" + ex.ToString());
				result = false;
				log = "数据异常";
				return true;
			}
			result = true;
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(result);
			this.PushIntoStack(log);
			this.PushIntoStack(tablesStr);
			this.PushIntoStack(title);
			this.PushIntoStack(dayScoreStr);
		}
	}
}
